#include "ShapesWindow.hpp"
#include "Square.hpp"
#include "Circle.hpp"
#include "Triangle.hpp"
using namespace std;

ShapesWindow::ShapesWindow( HINSTANCE hInstance )
	: Window( hInstance, "ShapesWindow" ), numShapes( 0 ), dragging( false )
{
	setTitle( "My Shapes Window" );

	addMenu( "&Shapes" );
	addMenuItem( 0, "New &Square",    NEW_SQUARE    );
	addMenuItem( 0, "New &Circle",    NEW_CIRCLE    );
	addMenuItem( 0, "New &Triangle",  NEW_TRIANGLE  );
}

ShapesWindow::~ShapesWindow()
{
	for (int i= 0; i < numShapes; i++)
		delete shapes[i];	
}

void ShapesWindow::paint( Canvas& canvas )
{
	Window::paint( canvas );

	for (int i= 0; i < numShapes; i++)
		shapes[i]->draw( canvas );
}

void ShapesWindow::mouseMove( int x, int y )
{
	if (dragging)
	{
		shapes[numShapes - 1]->move( x - lastx, y - lasty );
		lastx= x;
		lasty= y;
		requestRepaint();
	}
}

void ShapesWindow::mouseButtonDown( int x, int y )
{
	int hit= -1;

	for (int i= 0; i < numShapes; i++)
		if (shapes[i]->contains( x, y ))
			hit= i;

	if (hit > -1)
	{
		Shape* tmp= shapes[hit];
		for (int i= hit; i < numShapes - 1; i++)
			shapes[i]= shapes[i+1];
		shapes[numShapes - 1]= tmp;

		requestRepaint();

		dragging= true;
		lastx= x;
		lasty= y;
	}
}

void ShapesWindow::mouseButtonUp( int x, int y )
{
	dragging= false;
}

void ShapesWindow::mouseWheel( int x, int y, bool up )
{
	int hit= -1;

	for (int i= 0; i < numShapes; i++)
		if (shapes[i]->contains( x, y ))
			hit= i;

	if (hit > -1)
	{
		shapes[hit]->resize( up ? 10 : -10 );
		requestRepaint();
	}
}

void ShapesWindow::menuSelect( int id )
{
	if (numShapes >= MAX_SHAPES)
	{
		MessageBox( NULL, "I can't hold any more shapes!", "Max Shapes", MB_ICONWARNING | MB_OK );
	}
	else
	{
		Shape* newShape;

		COLORREF color= RGB( rand()%256, rand()%256, rand()%256 );

		switch (id)
		{
		case NEW_SQUARE:
			newShape= new Square( INIT_X, INIT_Y, INIT_SIZE, color );
			break;
		case NEW_CIRCLE:
			newShape= new Circle( INIT_X, INIT_Y, INIT_SIZE, color );
			break;
		case NEW_TRIANGLE:
			newShape= new Triangle( INIT_X, INIT_Y, INIT_SIZE, color );
			break;
		}

		shapes[numShapes++]= newShape;
		requestRepaint();
	}
}
